package com.njlime.sys.service;

import com.njlime.cms.service.sys.ChannelService;
import com.njlime.core.exception.BusinessException;
import com.njlime.core.exception.ParamException;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.repository.UnitDao;
import com.njlime.sys.repository.UnitWxConfigDao;
import com.njlime.sys.security.util.CacheUtils;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Dean on 2017-7-19.
 */
@Service
@Transactional(readOnly = true)
public class UnitService {

    @Resource
    private UnitDao unitDao;
    @Resource
    private ConfigService configService;
    @Resource
    private UnitWxConfigDao unitWxConfigDao;
    @Resource
    private ChannelService channelService;
    @Resource
    private UserConfigService userConfigService;


    public Map<String,Object> get(Integer id){
        return unitDao.getById(id);
    }

    public Unit findOne(Integer id){
        return unitDao.findOne(id);
    }

    /**
     * 获取单位列表
     * @param pageBean
     * @param unit
     * @return
     */
    public PageBean list(PageBean pageBean, Unit unit){
        return unitDao.list(pageBean,unit);
    }

    /**
     * 添加单位
     * @param unit
     */
    @Transactional(readOnly = false)
    public Unit addUnit(Unit unit){
        Unit parent = unitDao.findOne(unit.getParent_id());
        if(parent == null){
            throw new BusinessException("上级单位不正确");
        }
        unit.setParent_ids(parent.getParent_ids() + unit.getParent_id() + ",");
        Map<String,Object> ori = unitDao.getByName(unit.getUnit_name());
        if(ori != null){
            throw new BusinessException("名称已存在");
        }
        unit.setCreate_time(new Date());
        unit.setIs_del(GlobalValue.NO);
        unit.setLogin_flag(GlobalValue.YES);
        unit = unitDao.save(unit);
        CacheUtils.removeAll(UserUtils.USER_CACHE);
        if(GlobalValue.SYS_UNIT_ID.equals(unit.getParent_id())){
            configService.createByUnit(unit.getId());
            userConfigService.createDefault(unit.getId());
            channelService.createDefault(unit.getId());
        }
        return unit;
    }

    /**
     * 编辑单位
     * @param unit
     * @return
     */
    @Transactional(readOnly = false)
    public int editUnit(Unit unit){
        Map<String,Object> ori = unitDao.getByName(unit.getUnit_name());
        if(ori != null && !unit.getId().equals(Integer.parseInt(ori.get("id").toString()))){
            throw new BusinessException("单位名称已存在");
        }
        if(unit.getParent_id() != null){
            if(unit.getParent_id() == 0){
                unit.setParent_ids(unit.getParent_id() + ",");
            }else{
                Unit parent = unitDao.findOne(unit.getParent_id());
                if(parent == null){
                    throw new BusinessException("上级单位不正确");
                }
                if(unit.getParent_id().equals(unit.getId())){
                    throw new BusinessException("上级单位不正确");
                }
                unit.setParent_ids(parent.getParent_ids() + unit.getParent_id() + ",");
            }
        }
        if(unit.getStatus() != null){
            Unit oriUnit = unitDao.findOne(unit.getId());
            oriUnit.setStatus(unit.getStatus());
            unitDao.updateChildStatus(oriUnit);
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
        unit.setUpdate_time(new Date());
        unit.setUpdater(UserUtils.getUser().getId());
        return unitDao.updateUnit(unit);
    }

    /**
     * 批量删除
     * @param idArray
     */
    @Transactional(readOnly = false)
    public void deleteUnit(String[] idArray){
        if (idArray != null && idArray.length > 0) {
            for (String idStr : idArray) {
                Integer id = Integer.parseInt(idStr);
                int num = unitDao.countByParentId(id);
                if(num > 0){
                    throw new BusinessException("存在下级单位，不能删除");
                }
                configService.deleteByUnit(id);
                unitDao.deleteUnit(id);
            }
        }
        CacheUtils.removeAll(UserUtils.USER_CACHE);
    }

    /**
     * 获取单位树列表
     * @return
     */
    public List<Map<String,Object>> unitList(Unit rootUnit){
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<Unit> allUnit = unitDao.findAllList(rootUnit);
        String userUnits = getUserUnitString();
        if(allUnit != null && allUnit.size() > 0){
            for(Unit unit : allUnit){
                Map<String,Object> map = new HashMap<>();
                map.put("id",unit.getId());
                map.put("parent_id",unit.getParent_id());
                map.put("name",unit.getUnit_name());
                map.put("province_name",unit.getProvince_name());
                map.put("city_name",unit.getCity_name());
                map.put("area_name",unit.getArea_name());
                map.put("create_time",unit.getCreate_time());
                map.put("introduction",unit.getIntroduction());
                map.put("status",unit.getStatus());
                map.put("head_url",unit.getHead_url());
                if(userUnits.indexOf(unit.getId() + ",") == 0 || userUnits.indexOf("," + unit.getId() + ",") > 0){
                    map.put("disabled",false);
                }else{
                    map.put("disabled",true);
                }
                mapList.add(map);
            }
            if(rootUnit != null){
                mapList = treeBean(mapList, rootUnit.getId());
            } else {
                mapList = treeBean(mapList,GlobalValue.SYS_UNIT_ID);
            }
        }
        return mapList;
    }

    /**
     * 获取单位树
     * @return
     */
    public List<Map<String,Object>> unitTree(Unit rootUnit,Integer role_id){
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<Map<String,Object>> returnMapList = new ArrayList<>();
        List<Unit> allUnit = unitDao.findAllList(rootUnit);
        Map<String,Object> parentMap = new HashMap<>();
        String userUnits = getUserUnitString();
        String units = "";
        if(role_id != null){
            units = getRoleUnitString(role_id);
        }
        Integer root_unit_id = GlobalValue.SYS_UNIT_ID;
        if(rootUnit != null && rootUnit.getId() != null){
            root_unit_id = rootUnit.getId();
        }
        if(allUnit != null && allUnit.size() > 0){
            for(Unit unit : allUnit){
                Map<String,Object> map = new HashMap<>();
                map.put("id",unit.getId());
                map.put("parent_id",unit.getParent_id());
                map.put("name",unit.getUnit_name());
                if(userUnits.indexOf(unit.getId() + ",") == 0 || userUnits.indexOf("," + unit.getId() + ",") > 0){
                    map.put("disabled",false);
                }else{
                    map.put("disabled",true);
                }
                if(role_id != null){
                    if(units.indexOf(unit.getId() + ",") == 0 || units.indexOf("," + unit.getId() + ",") > 0){
                        map.put("checked", true);
                    }else {
                        map.put("checked", false);
                    }
                }
                mapList.add(map);
                if(unit.getId().equals(root_unit_id)){
                    parentMap = map;
                }
            }
            mapList = treeBean(mapList, root_unit_id);
            parentMap.put("children", mapList);
            returnMapList.add(parentMap);
            return returnMapList;
        }
        return mapList;
    }

    /**
     * 获取用户拥有的角色ID字符串
     * @return
     */
    private String getUserUnitString(){
        String unit_ids = "";
        List<Unit> unitList = UserUtils.getUnitList();
        if(unitList != null && unitList.size() > 0){
            for(int i = 0; i < unitList.size();i++){
                unit_ids += unitList.get(i).getId() + ",";
            }
        }
        return unit_ids;
    }

    /**
     * 获取角色拥有权限的单位
     * @return
     */
    private String getRoleUnitString(Integer role_id){
        String unit_ids = "";
        List<Map<String,Object>> unitList = unitDao.getUnitByRole(role_id);
        if(unitList != null && unitList.size() > 0){
            for(int i = 0; i < unitList.size();i++){
                unit_ids += unitList.get(i).get("id").toString()+ ",";
            }
        }
        return unit_ids;
    }

    /**
     * 递归获取树形结构
     * @param list
     * @param parent_id
     * @return
     */
    private List<Map<String,Object>> treeBean(List<Map<String,Object>> list, int parent_id){
        List<Map<String,Object>> nodeList = new ArrayList<>();
        for (Map<String,Object> map : list) {
            Integer pid = Integer.parseInt(map.get("parent_id").toString());
            Integer id = Integer.parseInt(map.get("id").toString());
            if (parent_id == pid) {
                List<Map<String,Object>> c_node = treeBean(list, id);
                map.put("children", c_node);
                nodeList.add(map);
            }
        }
        return nodeList;
    }

    /**
     * 根据角色id获取部门
     *
     * @param role_id
     * @return
     */
    public List<Map<String, Object>> getUnitByRole(Integer role_id) {
        return unitDao.getUnitByRole(role_id);
    }

    /**
     * 根据单位id获取系统单位的直属单位id（根单位id）
     * @param id
     * @return
     */
    public Integer getRootUnit(Integer id){
        Unit unit = unitDao.findOne(id);
        String[] units = unit.getParent_ids().replace(" ","").split(",");
        if(units.length >= 3){
            return Integer.parseInt(units[2]);
        }else if(units.length == 2){
            return id;
        }
        return null;
    }

    /**
     * 审核
     * @param unit
     * @return
     */
    @Transactional(readOnly = false)
    public int auditRegisterUnit(Unit unit){
        Unit ori = unitDao.findOne(unit.getId());
        if(ori == null || ori.getStatus() == GlobalValue.AUDITED){
            throw new ParamException("单位不正确");
        }
        unit.setStatus(GlobalValue.AUDITED);
        return unitDao.updateUnit(unit);
    }

    /**
     * 单位关联微信设置
     * @param unitWxConfig
     */
    public void addWxConfig(UnitWxConfig unitWxConfig){
        Unit unit = unitDao.findOne(unitWxConfig.getUnit_id());
        if(unit == null){
            throw new ParamException("单位不正确");
        }
        unitWxConfigDao.save(unitWxConfig);
    }

    /**
     * 根据单位id查询微信设置
     * @param unit_id
     * @return
     */
    public UnitWxConfig getWxConfig(Integer unit_id){
        return unitWxConfigDao.getWxConfig(unit_id);
    }

    public UnitWxConfig getWxConfigByAppid(String appid){
        return unitWxConfigDao.getWxConfigByAppid(appid);
    }


    public List<UnitWxConfig> getWxConfigList( ){
        return unitWxConfigDao.getWxConfigList( );
    }
    /**
     * 修改单位的微信公共号设置
     * @param unitWxConfig
     */
    @Transactional(readOnly = false)
    public void editUnitConfig(UnitWxConfig unitWxConfig,Integer userConfigId) {
        UnitWxConfig info = unitWxConfigDao.getWxConfig(unitWxConfig.getUnit_id());
        unitWxConfig.setWx_type(UnitWxConfig.WxType.SERVICE);
        if(info != null) {
            unitWxConfigDao.editUnitConfig(unitWxConfig);
        }else{
            unitWxConfigDao.save(unitWxConfig);
        }
        if(userConfigId != null){
            userConfigService.updateStatus(userConfigId);
        }
    }
}
